package com.cskaoyan.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @ConfigurationProperties注解的prefix属性值 + 成员变量名(set方法) = 配置文件中的key
 * @author stone
 * @date 2022/05/04 16:15
 */

@Configuration
@EnableConfigurationProperties(DatasourceProperties.class)
public class DataSourceConfiguration {

    /*@Autowired
    DatasourceProperties properties;*/

    DatasourceProperties properties;

    // 如果容器中的组件只包含一个有参构造方法，组件的实例化方式就会采用该有参构造方法
    // 形参 默认按照类型从容器中中取出组件
    public DataSourceConfiguration(DatasourceProperties properties) {
        this.properties = properties;
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(properties.getDriverClassName());
        dataSource.setUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());
        return dataSource;
    }
}
